//
//  ListViewController.swift
//  ColorNote
//
//  Created by 伏文东 on 2018/2/9.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit
import CoreData

class ListViewController: UITableViewController, NSFetchedResultsControllerDelegate {

    private var contents : [ContentMo] = []
    private var content : ContentMo!
    private var fc : NSFetchedResultsController<ContentMo>!
    
    // MARK: 懒加载属性
    private lazy var headPortrait: UIImageView = {
        
        let iv = UIImageView(frame: CGRect(x: 0,
                                           y: (kLetfBtnViewW - kHeadPortraitW) / 2,
                                           width: kHeadPortraitW,
                                           height: kHeadPortraitW))
        return iv
    }()
    
    private lazy var letfBtnView: UIView = {
        let lView = UIView(frame: CGRect(x: 0,
                                         y: 0,
                                         width: kLetfBtnViewW,
                                         height: kLetfBtnViewW))
        lView.backgroundColor = UIColor.clear
        lView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickInfo))
        lView.addGestureRecognizer(tap)
        return lView
    }()
    // MARK:  系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        notificationCenter()
        if !(kDefaults.bool(forKey: "ifFirst")) {
            //            for i in 1...7 {
            //                nllcontent2(i: i)
            //            }
            nllcontent()
        }
        DataExtensions.fetcAllData()
        fetchAll()
        showInfo()
    }
    
    private func notificationCenter()  {
        let notifiMycationName = NSNotification.Name(rawValue: "saveInfo")
        NotificationCenter.default.addObserver(self, selector: #selector(updateChange), name: notifiMycationName, object: nil)
    }
    @objc func updateChange() {
        showInfo()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private func showInfo() {
        let size = CGSize(width: kHeadPortraitW, height: kHeadPortraitW)
        guard let img = UIImage.navAvatarImage(image: UIImage(data: info.headPortrait!)!, size: size, backColor: UIColor.navColor()) else { return }
        headPortrait.image = img
    }
    
    private func nllcontent() {
        content = ContentMo(context: kContext)
        
        content.contentLabel = """
        欢迎使用彩色便签🤤
        
        彩色日记会把一周的7天分别以不一样的颜色展示给你
        
        每天给你不一样的感觉
        
        如果你每天坚持写一条日记
        
        7天之后你就会看到🌈哦！😂
        
        快去写一条吧🙈
        
        哈哈哈😂😂😂🤦🏻‍♂️🤤
        """
        content.dayLabel = "17"
        content.yearAndMonthLabel = "2017/2"
        content.timeLabel = "22:22"
        content.timestamp = 1
        content.dayOfWeek = 5
        
        info = UserInfoMo(context: kContext)
        let size = CGSize(width: 90, height: 90)
        info.headPortrait =  UIImageJPEGRepresentation(UIImage.avatarImage(image: #imageLiteral(resourceName: "头像2"), size: size)!, 0.5)
        info.sign = 1;
        try? kContext.save()
        
        kDefaults.set("小主", forKey: "name")
        kDefaults.set("😳你是不是忘了些什么？？.....", forKey: "introduce")
        
        kDefaults.set(true, forKey: "ifFirst")
    }
    
    private func nllcontent2(i: Int) {
        content = ContentMo(context: kContext)
        content.contentLabel = "😂😂😂😂😂"
        content.dayLabel = "\(22 + i)"
        content.yearAndMonthLabel = "2017/06"
        content.timeLabel = "22:22 "
        content.timestamp = 7 + Int64(i)
        content.dayOfWeek = Int64(i)
        try? kContext.save()
    }
    
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }
    
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }
    
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .delete:
            tableView.deleteRows(at: [indexPath!], with: .automatic)
        case .insert:
            tableView.insertRows(at: [newIndexPath!], with: .automatic)
        case .update:
            tableView.reloadRows(at: [indexPath!], with: .automatic)
            
        default:
            tableView.reloadData()
        }
        if let object = controller.fetchedObjects {
            contents = object as! [ContentMo]
        }
    }

    
    func fetchAll() {
        //步骤二：建立一个获取的请求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Content")
        let sd = NSSortDescriptor(key: "timestamp", ascending: false)
        fetchRequest.sortDescriptors = [sd]
        
        fc = NSFetchedResultsController(fetchRequest: fetchRequest,
                                        managedObjectContext: kContext,
                                        sectionNameKeyPath: nil, cacheName: nil) as! NSFetchedResultsController<ContentMo>
        fc.delegate = self
        //步骤三：执行请求
        do {
            try fc.performFetch()
            
            if let results = fc.fetchedObjects {
                contents = results
            }
            
        } catch  {
            fatalError("获取失败")
        }
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            kContext.delete(self.fc.object(at: indexPath))
            
            try? kContext.save()
        }
    }
    // MARK: 监听方法
    @objc private func clickAdd() {
        let post = PostViewController()
        let nav = UINavigationController(rootViewController: post)
        present(nav, animated: true, completion: nil)
    }
    @objc private func clickInfo() {
        let user = UserInfoViewController()
        let nav = UINavigationController(rootViewController: user)
        present(nav, animated: true, completion: nil)
    }
}

// MARK: - Table view data source
extension ListViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contents.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCellId", for: indexPath) as! MontentCell
        cell.content = contents[indexPath.row]
        
        cell.selectedBackgroundView = UIView()
        let labels: [UILabel] = [cell.contentLabel, cell.dayLabel, cell.yearAndMonthLabel,cell.timeLabel]
        switch contents[indexPath.row].dayOfWeek {
        case 1:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kWhite,
                       backgroundColor: kCheng,
                       selectColor: kSelectedCheng)
        case 2:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kBlack,
                       backgroundColor: kHuang,
                       selectColor: kSelectedHuang)
        case 3:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kWhite,
                       backgroundColor: kLv,
                       selectColor: kSelectedLv)
        case 4:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kBlack,
                       backgroundColor: kQing,
                       selectColor: kSelectedQing)
        case 5:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kWhite,
                       backgroundColor: kLan,
                       selectColor: kSelectedLan)
        case 6:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kWhite,
                       backgroundColor: kZi,
                       selectColor: kSelectedZi)
        default:
            customCell(cell: cell,
                       labels: labels,
                       textColor: kWhite,
                       backgroundColor: kChi,
                       selectColor: kSelectedChi)
        }
        
        return cell
    }
    
    private func customCell(cell: UITableViewCell,labels: [UILabel], textColor: UIColor, backgroundColor:UIColor, selectColor: UIColor)  {
        cell.backgroundColor = backgroundColor
        cell.selectedBackgroundView?.backgroundColor = selectColor
        for label in labels {
            label.textColor = textColor
        }
    }
    
    // MARK: 让分割线顶头
    override func viewDidLayoutSubviews() {
        tableView.separatorInset = UIEdgeInsets.zero
        tableView.layoutMargins = UIEdgeInsets.zero
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero
    }
}

// MARK: - Table view delegate
extension ListViewController {
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailVc = DetailViewController()
        detailVc.content = contents[tableView.indexPathForSelectedRow!.row]
        navigationController?.pushViewController(detailVc, animated: true)
    }
}

// MARK: - 设置UI界面
private extension ListViewController {
    func setupUI() {
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        setupNaviBar()
        
    }
    
    func setupNaviBar()  {
        letfBtnView.addSubview(headPortrait)
        
        let leftBtn = UIBarButtonItem.init(customView: letfBtnView)
        navigationItem.leftBarButtonItem = leftBtn
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "",
                                                                style: .plain,
                                                                target: nil,
                                                                action: nil)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
                                                            target: self,
                                                            action: #selector(clickAdd))
    }
}
































